//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.config;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author: Mr.gao
 * @Date: 2020/2/7 21:39
 * @Description: 每个服务访问五次，访问五次后切换到下一个可以访问的服务
 */

public class MyRandomRule extends AbstractLoadBalancerRule {

    private int total = 0;
    private int current = 0;

    public MyRandomRule() {
    }

    public Server choose(ILoadBalancer lb, Object key) {
        System.out.println("进入方法 MyRandomRule total : " + total + " current : " + current);
        if (lb == null) {
            return null;
        } else {
            Server server = null;

            while (server == null) {
                if (Thread.interrupted()) {
                    return null;
                }

                List<Server> upList = lb.getReachableServers();    //获取可到达的服务
                List<Server> allList = lb.getAllServers();      //获取所有的服务
                int serverCount = allList.size();              //所有服务的数量
                if (serverCount == 0) {
                    return null;
                }

//                int index = this.chooseRandomInt(serverCount);
//                server = (Server)upList.get(index);

                // ========================================================
                if (total < 5) {    //判断   是否已经访问五次
                    total++;
                    server = upList.get(current);     //如果没有   取出当前访问的服务器
                } else {
                    total = 1;
                    current++;                       // 否则切换到下一个可以访问的服务
                    if (upList.size() <= current ) {     // 如果超出最大可以访问的范围，计数器重置
                        current = 0;
                    }
                    server = upList.get(current);

                }

                // ========================================================
                if (server == null) {
                    Thread.yield();
                } else {
                    if (server.isAlive()) {
                        return server;
                    }

                    server = null;
                    Thread.yield();
                }
            }

            return server;
        }
    }

    protected int chooseRandomInt(int serverCount) {
        return ThreadLocalRandom.current().nextInt(serverCount);
    }

    public Server choose(Object key) {
        return this.choose(this.getLoadBalancer(), key);
    }

    public void initWithNiwsConfig(IClientConfig clientConfig) {
    }
}
